#!/bin/bash
set -e

# 检查并安装netcat（如果需要）
if ! command -v nc &> /dev/null; then
    echo "[INFO] 安装netcat..."
    yum install -y nc
fi

# 定义主机角色和IP地址映射关系
declare -A hosts=(
    ["192.168.4.254"]="mq-1-m"   # 主节点1
    ["192.168.4.125"]="mq-1-s"   # 从节点1
    ["192.168.4.237"]="mq-2-m"   # 主节点2
    ["192.168.4.175"]="mq-2-s"   # 从节点2
)

# 获取当前服务器的IP地址
current_ip=$(hostname -I | awk '{print $1}')

# 检查当前IP是否在定义的主机列表中
if [[ -z "${hosts[$current_ip]}" ]]; then
    echo "[ERROR] 当前服务器的IP地址 $current_ip 不在预定义的主机列表中"
    exit 1
fi

role=${hosts[$current_ip]}
echo "当前服务器的角色是: $role"

# 函数：下载并安装RocketMQ
install_rocketmq() {
    echo "[INFO] 正在下载并解压RocketMQ..."
    wget -P /tmp "http://oss.wuyou.run/software/rocketmq/rocketmq-4.9.3.tar.gz" || { echo "[ERROR] 下载失败"; exit 1; }
    tar -xzf "/tmp/rocketmq-4.9.3.tar.gz" -C /opt/ || { echo "[ERROR] 解压失败"; exit 1; }
    ln -sf "/opt/rocketmq-4.9.3" /opt/rocketmq
}

# 函数：配置和启动NameServer
setup_nameserver() {
    echo "[INFO] 正在启动NameServer..."
    mkdir -p /opt/rocketmq/logs
    nohup sh /opt/rocketmq/bin/mqnamesrv > /opt/rocketmq/logs/namesrv.log 2>&1 &
    # 等待NameServer启动，检测9876端口
    echo "[INFO] 等待NameServer启动..."
    while ! nc -z localhost 9876; do
        sleep 1
    done
}

# 函数：配置和启动Broker
setup_broker() {
    local ip=$1
    local role=$2
    broker_name=$(echo $role | awk -F '-' '{print $1"-"$2}')
    broker_id=$(echo $role | awk -F '-' '{if ($3 == "m") print 0; else print 1}')
    
    echo "[INFO] 正在为${broker_name}（角色：${role}）配置Broker..."
    mkdir -p "/opt/rocketmq/conf/${broker_name}"
    config_file="/opt/rocketmq/conf/${broker_name}/broker.properties"
    
    # 生成Broker配置文件
    cat <<EOF > "${config_file}"
brokerClusterName=DefaultCluster
brokerName=${broker_name}
brokerId=${broker_id}
brokerIP1=${ip}
namesrvAddr=192.168.4.254:9876;192.168.4.237:9876
listenPort=10911
storePathRootDir=/opt/rocketmq/store/${broker_name}
autoCreateTopicEnable=true
fileReservedTime=48
deleteWhen=04
brokerRole=SLAVE
flushDiskType=ASYNC_FLUSH
EOF

    # 根据角色调整配置
    if [[ $role =~ .*-m$ ]]; then
        sed -i 's/brokerRole=SLAVE/brokerRole=SYNC_MASTER/' "${config_file}"
        sed -i 's/flushDiskType=ASYNC_FLUSH/flushDiskType=SYNC_FLUSH/' "${config_file}"
    fi

    echo "[INFO] 正在启动Broker ${broker_name}..."
    mkdir -p "/opt/rocketmq/logs/${broker_name}"
    nohup sh "/opt/rocketmq/bin/mqbroker" -c "${config_file}" > "/opt/rocketmq/logs/${broker_name}/broker.log" 2>&1 &
}

# 创建rocketmq-namesrv.service
cat <<EOF | tee /etc/systemd/system/rocketmq-namesrv.service > /dev/null
[Unit]
Description=RocketMQ Name Server
After=network.target

[Service]
Type=forking
User=root
ExecStart=/opt/rocketmq/bin/mqnamesrv
ExecStop=/opt/rocketmq/bin/mqshutdown namesrv
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

# 创建rocketmq-broker@.service模板
cat <<EOF | tee /etc/systemd/system/rocketmq-broker@.service > /dev/null
[Unit]
Description=RocketMQ Broker (%i)
After=network.target rocketmq-namesrv.service

[Service]
Type=forking
User=root
EnvironmentFile=-/etc/sysconfig/rocketmq-%i
ExecStart=/opt/rocketmq/bin/mqbroker -c \${CONFIG_FILE}
ExecStop=/opt/rocketmq/bin/mqshutdown broker
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

# 配置每个Broker的环境变量文件
broker_name=$(echo $role | awk -F '-' '{print $1"-"$2}')
mkdir -p /etc/sysconfig
cat <<EOF | tee /etc/sysconfig/rocketmq-${broker_name} > /dev/null
CONFIG_FILE="/opt/rocketmq/conf/${broker_name}/broker.properties"
EOF

# 执行安装和配置
install_rocketmq

# 仅主节点启动NameServer
if [[ $role =~ .*-m$ ]]; then
    setup_nameserver
fi

# 配置并启动Broker
setup_broker "$current_ip" "$role"

# 仅主节点启用NameServer
if [[ $role =~ .*-m$ ]]; then
    systemctl enable rocketmq-namesrv.service
fi

# 启用并启动Broker
systemctl enable rocketmq-broker@${broker_name}.service

# 加载新的服务单元文件
systemctl daemon-reload

echo "RocketMQ部署完成并且已配置开机启动。请重启服务器以验证设置。"